package com.example.leaderapplication.View.Fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.example.leaderapplication.Base.BaseConfig;
import com.example.leaderapplication.Base.BaseFragment;
import com.example.leaderapplication.R;
import com.example.leaderapplication.Utils.SPUtil;
import com.example.leaderapplication.Utils.ToastUtil;
import com.example.leaderapplication.View.Activity.CompreDisplayActivity;

public class AnalyseFragment extends BaseFragment {
    protected View rootView;
    WebView mWebView;



    // H5 的引入
    private String productOnlyNo;
    private String webviewurl;
    private String path;
    //刷新
    protected boolean isCreated = false;

    private static AnalyseFragment homePageFragment;

    public static AnalyseFragment getInstance() {
        if (homePageFragment == null) {
            homePageFragment = new AnalyseFragment();
        }
        return homePageFragment;
    }

    @Override
    public View setView(LayoutInflater inflater) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_analys, null);

        }
        return rootView;
    }

    @Override
    public void initView() {

        // 标记
        isCreated = true;

        mWebView = (WebView) view.findViewById(R.id.compre_webview);

    }

    @Override
    public void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isCreated) {
            return;
        }

        // 这个地方 每次到这个界面都会从新加载 数据
        if (isVisibleToUser) {
            initWebView();
        }

    }

    private void initWebView() {
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true); //设置可以访问文件
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        mWebView.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
        mWebView.getSettings().setBlockNetworkImage(false);//解决图片不显示
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");//设置编码格式

        // 这是h5 交互
        mWebView.addJavascriptInterface(new schedule(), "booking");
        mWebView.addJavascriptInterface(new noLogin(), "noLogin");

        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String token;
                token = (String) SPUtil.get(getContext(), BaseConfig.ACCESS_TOKEN, "");

                String method = "javascript:getToken(\"" + token + "\")";
                mWebView.loadUrl(method);

            }

            @Override
            public void onLoadResource(WebView view, String url) {
                webviewurl = view.getUrl();
                super.onLoadResource(view, url);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                try {
                    //iosLoadDialog.show();
                } catch (Exception e) {
                    Log.e("erro", Log.getStackTraceString(e));
                }
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null)
                    return false;
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
//                    ToastUtils.showShort("暂无应用打开此链接");
                    }
                    return true;
                }

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();// 接受所有网站的证书
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

        });

        // 这里 做页面跳转
        String onlineUrl = (String) SPUtil.get(getContext(), BaseConfig.ANALYSE_PATH, "");
//        String onlineUrl = BaseConfig.WEB_Base_URL + "#/pages/comprehensiveDisplay/comprehensiveDisplay";
//        String onlineUrl = "http://192.168.20.58:8081/#/pages/comprehensiveDisplay/comprehensiveDisplay";
        mWebView.loadUrl(onlineUrl);
    }

    private final class schedule {
        /**
         * 注意这里的@JavascriptInterface注解， target是4.2以上都需要添加这个注解，否则无法调用
         *
         * @param text
         */
        @JavascriptInterface
        public void schedule(String text, String businessOrgId, String destinationID, String destinationType) {

            //  这个地方  验证用户是否登入， 如果登入那么就去跳转页面
//            if (userInfo != null) {
//                productOnlyNo = text;
//            } else {
//                Intent intent = new Intent(CompreDisplayActivity.this, LoginActivity.class);
//                startActivity(intent);
//            }

        }

    }

    @SuppressWarnings("unused")
    private final class noLogin {
        /**
         * 注意这里的@JavascriptInterface注解， target是4.2以上都需要添加这个注解，否则无法调用
         */
        @JavascriptInterface
        public void noLogin(String text) {
            // ToastUtil.shortToast(OrderDetailsWebActivity.this,orderBatchId);
            ToastUtil.showToast("用户登录失效");
        }
    }
}
